package com.sinodata.bsm.cicp.collector.apache;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CollectorUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-20 15:29:33      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class ApacheStatusCollector extends Collector {

    private static final Logger logger = Logger.getLogger(ApacheStatusCollector.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String url = this.getParamMap().get("URLAddress").trim();

        List<ResPropertyValue> retList = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        String url1 = null;
        if (url.endsWith("/")) {
            url1 = url + "server-status?auto";
        } else {
            url1 = url + "/server-status?auto";
        }
        String respXml;
        String values;

        try {
            respXml = CollectorUtil.getHttpXml(url1);
        } catch (Exception e) {
            logger.error("failed to collect apache status", e);
            throw new CollectorException(e);
        }

        String[] respRow = respXml.split("\n");
        for (int i = 0; i < respRow.length - 1; i++) {
            String[] respCloumn = respRow[i].split(":");
            values = respCloumn[1].trim();
            propValues[i] = ResPropertyValue.createPropValue(values, propMetas[i]);
        }

        propertyValueX.setValues(propValues);
        retList.add(propertyValueX);
        return retList;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "URLAddress" };
    }

    @Override
    public String[] getPropMeta() {
        //       return new String[] { "TotalAccessTimes", "TotalAccessAccount", "StartTime", "RequestsNumPerSecond", "DataVolumePerSecond", "AvgRequestCreateDataVlume", "BusyWorkersNum", "FreeWorkersNum" };
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8" };
    }
}
